package com.bigbigrain.jiagou.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @description: 图片防盗链
 * @author: B1gB1gRA1n
 * @create: 2020-4-17 15:14
 **/
@WebFilter(filterName = "imgFilter", urlPatterns = "/img/*")
public class ImgFilter implements Filter {

    @Value("${domain.name}")
    private String domainName;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 1.获取请求头中的来源字段
        HttpServletRequest req = (HttpServletRequest) request;
        String referer = req.getHeader("Referer");
        if (StrUtil.isEmpty(referer)) {
            request.getRequestDispatcher("/imgs/error.png").forward(req, response);
            return;
        }
        // 2.判断请求头中的域名是否和限制的域名一致
        String domainUrl = URLUtil.toURI(referer).getHost();
        // 正常情况 黑名单 白名单接口
        if (!domainUrl.equals(domainName)) {
            request.getRequestDispatcher("/imgs/error.png").forward(req, response);
            return;
        }
        // 直接放行图片
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {

    }
}
